package com.starbaba.mainicon.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.FileCopyUtils;

import com.alibaba.fastjson.JSON;
import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.http.HttpClientUtil;
import com.base.common.http.model.FormData;
import com.base.common.http.model.HttpResult;
import com.base.common.http.model.PostData;
import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jumai.server.common.util.TestMode;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.opensymphony.xwork2.Action;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.channel.model.ProductChannelVO;
import com.starbaba.core.hibernate.Page;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.core.web.struts2.BaseListVO;
import com.starbaba.core.web.struts2.JsonResult;
import com.starbaba.core.web.translate.TranslateVO;
import com.starbaba.mainicon.model.MainiconControlVO;
import com.starbaba.model.bean.BadgeInfo;
import com.starbaba.model.dao.CommObjImgDao;
import com.starbaba.model.db.Comm_Sys_Code;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.dictionary.IBadgeState;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.model.utils.NumberUtil;
import com.starbaba.model.utils.SourceUtils;
import com.starbaba.model.utils.ZipUtil;
import com.starbaba.system.syscode.model.SyscodeVO;
import com.starbaba.tools.sequence.Sequence;
import com.starbaba.utils.LifeConstant;
import com.tuanzi.server.loan_base.model.bean.loan.BannerIconCondition;
import com.tuanzi.server.loan_base.util.SendEmail;

import net.sf.json.JSONArray;

@SuppressWarnings({"deprecation","unchecked"})
public class MainiconControlAction extends BaseAction {

    private static final long serialVersionUID = 1L;

    private String savePath;

	private String uploadFileName;

	private File upload;
	
	private File upload_click;

	private String upload_clickFileName;
	
	private String uploadContentType;

	private File uploadTitleUrl;
	private String uploadTitleUrlFileName;
	private String uploadTitleUrlContentType;

	public MainiconControlAction() {
		this.voClass = MainiconControlVO.class;
		this.pkNameArray = new String[] { "id" };
	}

	public void beforeAdd() {

	}

	public String save() {
		return super.save();
	}

	
	@Override
	public String show() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		super.show();
		return Action.SUCCESS;
	}

	public void data() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(
					Struts2Utils.getRequest(), paramsMap);

			// 根据页面传过来的控制数据，构造页面数据请求
			parsePageRequest();

			page = new Page();
			page.setPageNo(pageRequest.getIDisplayStart()
					/ pageRequest.getIDisplayLength() + 1);
			page.setPageSize(pageRequest.getIDisplayLength());

			// 单表EntityListVO
			BeanUtils.copyProperties(this.getEntityListVO(), page);
			this.setParamsMapToTargetObject(paramsMap, this.getEntityListVO());

			((BaseListVO) this.getEntityListVO()).setOrder(pageRequest
					.getOrder());
			((BaseListVO) this.getEntityListVO()).setOrderBy(pageRequest
					.getOrderby());

			// 查询前处理,包含权限控制等
			beforeData();

			// 数据查询
			queryData();

			// 查询后处理,数据解析、封装
			afterData();

			returnData();
		} catch (Exception ex) {
			ex.printStackTrace();
			this.addActionMessage(ex.getMessage());
		}
	}
	
	@Override
	protected void beforeShow() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		List<TranslateVO> list = new ArrayList<TranslateVO>();
		list.add(new TranslateVO("0", "已下线"));
		list.add(new TranslateVO("1", "已上线"));
		paramsMap.put("statusList", list);
		list = new ArrayList<TranslateVO>();
		list.add(new TranslateVO("android", "android"));
		list.add(new TranslateVO("ios", "ios"));
		paramsMap.put("platformList", list);
		List<TranslateVO> types = LifeConstant.getSysCodeTranslate("icontype");
		paramsMap.put("types", types);
		paramsMap.put("type", 1);
		paramsMap.put("productlist", getProductList());
	}

	public String getBase() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		prepareBase();
		String id = (String) paramsMap.get("id");
		String type = (String) paramsMap.get("type");
		paramsMap.put("type", type);
		MainiconControlVO vo = null;
		if (StringUtils.isNotEmpty(id)) {
			vo = (MainiconControlVO) this.getService().findUniqueByHQL(" From MainiconControlVO vo where vo.id = ? ", Long.valueOf(id));
		}
		if (vo != null) {
			paramsMap.put("channel", vo.getChannel().toString());
			paramsMap.put("platform", vo.getPlatform());
			paramsMap.put("position", vo.getPosition());
			paramsMap.put("orderNum", vo.getOrderNum());
			paramsMap.put("isTitleBarImmerse",vo.getIsTitleBarImmerse());
			paramsMap.put("isMyIconWhite",vo.getIsMyIconWhite());
			paramsMap.put("titleUrl",vo.getTitleUrl());
			// paramsMap.put("title", vo.getTitle());
			if(StringUtils.isNotEmpty(vo.getTitle())){
				paramsMap.put("title", vo.getTitle().replace("\"", "&quot;"));
			}else{
				paramsMap.put("title", "");
			}
			paramsMap.put("imgurl", CommObjImgDao.dealWidthUrl(vo.getImgurl()));
			paramsMap.put("af_click_imgurl", CommObjImgDao.dealWidthUrl(vo.getAf_click_imgurl()));
			paramsMap.put("targetUrl", vo.getTargeturl());
			if(null != vo.getDisplay_way()){
				paramsMap.put("displayWay", vo.getDisplay_way().toString());
			}
			paramsMap.put("api", vo.getApi());
			paramsMap.put("type", type);
			if (vo.getMinVersionCode() != null) {
				paramsMap.put("minVersionCode", vo.getMinVersionCode().toString());
			}
			if (vo.getMaxVersionCode() != null) {
				paramsMap.put("maxVersionCode", vo.getMaxVersionCode().toString());
			}
			if (vo.getStartTime() != null) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String date = format.format(vo.getStartTime());
				paramsMap.put("startTime", date);
			}
			if (vo.getEndTime() != null) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String date = format.format(vo.getEndTime());
				paramsMap.put("endTime", date);
			}
			if (vo.getCityids() != null) {
			    String cityids = vo.getCityids();
			    if(StringUtils.isNotEmpty(cityids)){
			        paramsMap.put("cityids",cityids.replace("[", "").replace("]", "").replaceAll("\"",""));
			    }
			}
			if (vo.getValue() != null) {
				paramsMap.put("value", vo.getValue().replace("\"", "&quot;"));
			}
			if (vo.getOpenType() != null) {
				paramsMap.put("launch", vo.getOpenType());
			}
			if (vo.getMustLogin() != null && vo.getMustLogin() == 1) {
				paramsMap.put("mustLogin", "1");
			} else {
				paramsMap.put("mustLogin", "0");
			}
			if (StringUtils.isNotEmpty(vo.getBadge())) {
				BadgeInfo info = JSONUtils.fromJsonNew(vo.getBadge(), BadgeInfo.class);
				paramsMap.put("badgeresident", info.getResident());
				paramsMap.put("badgestate", info.getState());
				paramsMap.put("badgetext", info.getText());
			} else {
				paramsMap.put("badgetext", "");
			}
			paramsMap.put("productlist", getProductList());
			paramsMap.put("data_key", vo.getData_key());
			
			if (vo.getExcept_channel() != null){
				paramsMap.put("except_channel", vo.getExcept_channel().replace("[", "").replace("]", ""));
			}
			
			if(StringUtils.isNotBlank(vo.getBusiness_condition())) {
				BannerIconCondition bannerIconCondition = JSONUtils.fromJsonNew(vo.getBusiness_condition(), BannerIconCondition.class);
				if(bannerIconCondition.conditonType != null) {
					paramsMap.put("conditonType", bannerIconCondition.conditonType);
				}
				if(StringUtils.isNotBlank(bannerIconCondition.conditonValue)) {
					/**
					 * 解决由于值中的双引号与input标签中value属性的双引号冲突，value将值中第一个双引号误认为引号结束。
					 * 将双引号转义后的内容显示在input文本框中, &quot;在显示时，仍会显示为双引号
					 */
					paramsMap.put("conditonValue", bannerIconCondition.conditonValue.replaceAll("\"","&quot;"));
				}
				if(bannerIconCondition.bannerIconId != null) {
					paramsMap.put("iconId", bannerIconCondition.bannerIconId);
				}
			}
			
			
		}
		return Action.SUCCESS;
	}

	private ArrayList<TranslateVO> getProductList() {
		ArrayList<TranslateVO> list = new ArrayList<TranslateVO>();
//		list.add(new TranslateVO("9999", "全部"));
		String sql = "select DISTINCT prdid AS code, name AS kindname from comm_product_prdid";
		List<Object> params = new ArrayList<Object>();
		BaseDao dao = new BaseDao(Constant.POOL_LIFE);
		try {
			List<Comm_Sys_Code> result = dao.list(sql, Comm_Sys_Code.class,params);
			if(null != result && result.size() > 0){
				for(Comm_Sys_Code sc : result){
					list.add(new TranslateVO(String.valueOf(sc.getCode()),sc.getKindname()));
				}
			}
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	private void prepareBase() throws Exception {
		ArrayList<TranslateVO> channels = getChannel();
		paramsMap.put("channelList", channels);
		TranslateVO android = new TranslateVO("android", "android");
		TranslateVO ios = new TranslateVO("ios", "ios");
		ArrayList<TranslateVO> platformList = new ArrayList<TranslateVO>();
		platformList.add(android);
		platformList.add(ios);
		paramsMap.put("platformList", platformList);
		List<SyscodeVO> list = LifeConstant.getSysCode("iconaction");
		paramsMap.put("launchParamList", list);
		List<SyscodeVO> badgestateList = LifeConstant.getSysCode("badgestate");
		paramsMap.put("badgestateList", badgestateList);
		List<SyscodeVO> badgeresidentList = LifeConstant.getSysCode("badgeresident");
		paramsMap.put("badgeresidentList", badgeresidentList);
		ArrayList<TranslateVO> loginList = new ArrayList<TranslateVO>();
		loginList.add(new TranslateVO("0", "不需要"));
		loginList.add(new TranslateVO("1", "需要"));
		ArrayList<TranslateVO> displayWayList = new ArrayList<TranslateVO>();
		displayWayList.add(new TranslateVO("0", "总是显示"));
		displayWayList.add(new TranslateVO("1", "未登录显示"));
		displayWayList.add(new TranslateVO("2", "登录显示"));
		displayWayList.add(new TranslateVO("3", "根据缓存结果显示"));
		displayWayList.add(new TranslateVO("4", "老用户显示"));
		displayWayList.add(new TranslateVO("5", "根据点击次数(只支持短链接)"));
		displayWayList.add(new TranslateVO("6", "新用户显示"));
		ArrayList<TranslateVO> isList = new ArrayList<TranslateVO>();
		isList.add(new TranslateVO("0", "否"));
		isList.add(new TranslateVO("1", "是"));
		paramsMap.put("displayWayList", displayWayList);
		paramsMap.put("loginList", loginList);
		paramsMap.put("productlist", getProductList());
		paramsMap.put("isList",isList);
		
		List<TranslateVO> bannerConditionList = Lists.newArrayList();
		bannerConditionList.add(new TranslateVO("", "不限定条件"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.CREATED_ZHENGXIN), "创建过征信订单"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.CREATED_GALAXY_CARD), "创建过银河黑卡订单"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.CLICK_LOAN_ACTIVITY), "点击过某个贷款活动"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.IS_NEW_PHONE_ID), "新设备首日出现"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.IS_EXIST_LOAN_USER_INFO), "已创建资料"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.BANANA_BIND_CARD), "是否绑卡（布拿拿）"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.BANANA_BIND_CARD_COUNT), "绑卡数（在替换值输入数字）"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.BANANA_CARD_BILL_BALANCE), "账单金额与剩余额度的比值（在替换值输入数字）"));
		bannerConditionList.add(new TranslateVO(String.valueOf(BannerIconCondition.BANANA_CHECK_USER), "撞库结果为老用户"));
		paramsMap.put("iconConditionList", bannerConditionList);
	}

    public ArrayList<TranslateVO> getChannel() throws Exception {
		List<ProductChannelVO> list = (List<ProductChannelVO>) this.getService().doFindALL(ProductChannelVO.class);
		ArrayList<TranslateVO> channels = new ArrayList<TranslateVO>();
		for (ProductChannelVO vo : list) {
			channels.add(new TranslateVO(vo.getChannelCode().toString(), vo.getChannelName()));
		}
		return channels;
	}

	@Override
	public void queryData() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String platform = (String) paramsMap.get("platform");
			String position = (String) paramsMap.get("position");
			String prdid = (String) paramsMap.get("prdid");
			page = getPage();
			MainiconControlListVO vo = (MainiconControlListVO) this.entityListVO;
			vo.set_ieq_status((String) paramsMap.get("status"));
			vo.set_ieq_type((String) paramsMap.get("type"));
			if (StringUtils.isNotEmpty(platform)) {
				vo.set_seq_platform(platform);
			}
			if (StringUtils.isNotEmpty(position)) {
				vo.set_ieq_position(position);
			}
			if (StringUtils.isNotEmpty(prdid)) {
				vo.set_sk_app_prd_id(prdid);
			}
			vo.setOrderBy("status desc, platform ,channel, position ,orderNum");
			page = this.getService().doQuery(MainiconControlVO.class, vo);
			
            List<MainiconControlVO> datas = page.getDatas();
			for (MainiconControlVO iconVO : datas) {
				iconVO.setImgurl(CommObjImgDao.dealWidthUrl(iconVO.getImgurl()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String saveBase() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		try {
  			String id = (String) paramsMap.get("id");
			String app_prd_id = null;
			if(paramsMap.get("category") instanceof String){
				app_prd_id = (String)paramsMap.get("category");
			}else{
				String[] categories = (String [])paramsMap.get("category");
				if(null != categories && categories.length > 0){
					int i = 0;
					for(String iid : categories){
						i =  i + 1;
						if(i == 1){
							app_prd_id = iid;
						}else{
							app_prd_id = app_prd_id + "#" + iid;
						}
					}
				}
			}
			
			String channel = (String) paramsMap.get("channel");
			String platform = (String) paramsMap.get("platform");
			String maxVersionCode = (String) paramsMap.get("maxVersionCode");
			String minVersionCode = (String) paramsMap.get("minVersionCode");
			String startTime = (String) paramsMap.get("startTime");
			String endTime = (String) paramsMap.get("endTime");
			String position = (String) paramsMap.get("position");
			String orderNum = (String) paramsMap.get("orderNum");
			String mustLogin = (String) paramsMap.get("mustLogin");
			if (StringUtils.isEmpty(orderNum)) {
				throw new IllegalStateException("顺序不能为空");
			}
			String type = (String) paramsMap.get("type");
			String oldimg = (String) paramsMap.get("oldimg");
			if (StringUtils.isNotEmpty(oldimg)) {
				oldimg = oldimg.replace(SourceUtils.NGIX_HOST, "").replace(SourceUtils.QINIU_HOST, "");
			}
			String newimg = (String) paramsMap.get("newimg");
			if (StringUtils.isNotEmpty(newimg)) {
				newimg = newimg.replace(SourceUtils.NGIX_HOST, "").replace(SourceUtils.QINIU_HOST, "");
			}
			
			String cityids = (String) paramsMap.get("cityids");
			if(StringUtils.isNotEmpty(cityids)){
			    String[] arr_cityid = cityids.split(",");
			    cityids = String.valueOf(JSONUtils.toJsonArray(arr_cityid));
			}

			String launch = (String) paramsMap.get("launch");
			
			String badgestate = (String) paramsMap.get("badgestate");
			String badgestext = (String) paramsMap.get("badgetext");
			String badgeresident = (String) paramsMap.get("badgeresident");
			String value = (String) paramsMap.get("value");
			String dataKey = (String) paramsMap.get("data_key");
			
			String operator = this.userVO.getUsername();
			
			if (StringUtils.isNotEmpty(value) && "4".equals(launch)) {
				try {
					JSON.parse(value);
				} catch (Exception e) {
					paramsMap.put("status", -1);
					paramsMap.put("msg", "launch param不是json格式");
					prepareBase();
					return Action.ERROR;
				}
			}

			int bannerType = Integer.parseInt(type);
			if (bannerType == -1) {
				if (StringUtils.isNotEmpty(id)) {
					this.getService().executeHQLUpdate("update MainiconControlVO vo set vo.status = 0 where vo.id = ?", Long.valueOf(id));
				}
				String selectHql = "From MainiconControlVO vo where vo.status=1 AND vo.channel = ? and vo.platform= ? and vo.position = ? and vo.type = ?";
				
				if (StringUtils.isNotEmpty(app_prd_id)) {
					selectHql += "and vo.app_prd_id = ?";
				}
				if (maxVersionCode != null && minVersionCode != null) {
					selectHql += " AND ((vo.minVersionCode <= " + Integer.valueOf(minVersionCode) + " AND vo.maxVersionCode >=" + Integer.valueOf(minVersionCode) + ")"
							+ " OR (vo.minVersionCode <= " + Integer.valueOf(maxVersionCode) + " AND vo.maxVersionCode >=" + Integer.valueOf(maxVersionCode) + ")"
							+ " OR (vo.minVersionCode >= " + Integer.valueOf(minVersionCode) + " AND vo.maxVersionCode <=" + Integer.valueOf(maxVersionCode) + "))";
				} else if (minVersionCode != null) {
					selectHql += " AND (vo.maxVersionCode >= " + Integer.valueOf(minVersionCode) + " OR (vo.maxVersionCode is null  AND vo.minVersionCode is not null))";
				} else if (maxVersionCode != null) {
					selectHql += " AND (vo.minVersionCode <= " + Integer.valueOf(maxVersionCode) + " OR (vo.minVersionCode is null  AND vo.maxVersionCode is not null))";
				}

				if (startTime != null && endTime != null) {
					selectHql += " AND ((vo.startTime <= '" + startTime + "' AND vo.endTime >='" + startTime + "')" + " OR (vo.startTime <= '" + endTime + "' AND vo.endTime >='"
							+ endTime + "')" + " OR (vo.startTime >= '" + startTime + "' AND vo.endTime <='" + endTime + "'))";
				} else if (startTime != null) {
					selectHql += " AND (vo.endTime >= " + Integer.valueOf(minVersionCode) + " OR (vo.endTime is null AND vo.startTime is not null))";
				} else if (endTime != null) {
					selectHql += " AND (vo.startTime <= " + Integer.valueOf(maxVersionCode) + " OR (vo.startTime is null AND vo.endTime is not null))";
				}

				List<MainiconControlVO> vo = (List<MainiconControlVO>) this.getService().doFindByHQL(selectHql, Integer.valueOf(channel), platform, Integer.valueOf(position),bannerType);
				if (vo != null && vo.size() != 0) {
					if (StringUtils.isNotEmpty(id)) {
						this.getService().executeHQLUpdate("update MainiconControlVO vo set vo.status = 1 where vo.id = ?", Long.valueOf(id));
					}
					paramsMap.put("status", -1);
					paramsMap.put("msg", "错误：录入信息与现在数据有重叠，请检查");
					prepareBase();
					return Action.SUCCESS;
				}
			}
			
			JSONArray jsonArrayChannel = new JSONArray();
			String exceptChannel = (String) paramsMap.get("except_channel");
			if(StringUtils.isNotEmpty(exceptChannel)){
				String [] arrExceptChannel = exceptChannel.split(",");
				int [] newArrExceptChannel = new int [arrExceptChannel.length];
				for (int i = 0; i < arrExceptChannel.length; i++) {
					newArrExceptChannel[i] = Integer.parseInt(arrExceptChannel[i]);
				}
				jsonArrayChannel = JSONArray.fromObject(newArrExceptChannel);
			}
			
			MainiconControlVO vo = null;
			if (StringUtils.isNotEmpty(id)) {
				vo = (MainiconControlVO) this.getService().findUniqueByHQL(" From MainiconControlVO vo where id = ?", Long.valueOf(id));
			}
			MainiconControlVO bannerControlVO = new MainiconControlVO();
			bannerControlVO.setId(Sequence.getSequence());
			bannerControlVO.setChannel(Integer.valueOf(channel));
			bannerControlVO.setPlatform(platform);
			bannerControlVO.setType(bannerType);
			bannerControlVO.setImgurl(oldimg);
			bannerControlVO.setAf_click_imgurl(newimg);
			bannerControlVO.setOpenType(Integer.parseInt(launch));
			bannerControlVO.setData_key(dataKey);
			
			if (StringUtils.isNotEmpty(app_prd_id)) {
				bannerControlVO.setApp_prd_id(app_prd_id);
			}
			if (StringUtils.isNotEmpty(cityids)) {
				bannerControlVO.setCityids(cityids);
				paramsMap.put("cityids", cityids);
			}
			if (getUploadFileName() != null) {
				String dstPath = ServletActionContext.getServletContext().getRealPath(this.getSavePath());
				File out = new File(dstPath);
				if (!out.exists()) {
					out.mkdirs();
				}
				dstPath += File.separator + getUploadFileName();
				out = new File(dstPath);
				FileCopyUtils.copy(upload, out);
				FileInputStream in = new FileInputStream(dstPath);
				// Zone为七牛机房所在地，根据源所在机房配置
		        Configuration config = new Configuration(Zone.zone0()); 
		        String imgUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
		        in.close();
				
				bannerControlVO.setImgurl(imgUrl);
			}
			if (getUpload_clickFileName() != null) {
				String dstPath = ServletActionContext.getServletContext().getRealPath(this.getSavePath());
				File out = new File(dstPath);
				if (!out.exists()) {
					out.mkdirs();
				}
				dstPath += File.separator + getUpload_clickFileName();
				out = new File(dstPath);
				FileCopyUtils.copy(upload_click, out);
				FileInputStream in = new FileInputStream(dstPath);
				// Zone为七牛机房所在地，根据源所在机房配置
		        Configuration config = new Configuration(Zone.zone0()); 
		        String imgUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
		        in.close();
				bannerControlVO.setAf_click_imgurl(imgUrl);
			}
			if (minVersionCode != null) {
				bannerControlVO.setMinVersionCode(Integer.valueOf(minVersionCode));
			}
			if (maxVersionCode != null) {
				bannerControlVO.setMaxVersionCode(Integer.valueOf(maxVersionCode));
			}
			if (startTime != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(startTime);
				bannerControlVO.setStartTime(date);
			}
			if (endTime != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(endTime);
				bannerControlVO.setEndTime(date);
			}
			bannerControlVO.setPosition(Integer.valueOf(position));
			bannerControlVO.setOrderNum(Integer.valueOf(orderNum));
			bannerControlVO.setTitle((String) paramsMap.get("title"));
			bannerControlVO.setTargeturl((String) paramsMap.get("targetUrl"));
			bannerControlVO.setDisplay_way(Integer.valueOf(paramsMap.get("displayWay").toString()));
			bannerControlVO.setValue(value);
			String isTitleBarImmerse =  (String)paramsMap.get("isTitleBarImmerse");
			String isMyIconWhite =  (String) paramsMap.get("isMyIconWhite");
			if (StringUtils.isBlank((isTitleBarImmerse))){
				bannerControlVO.setIsTitleBarImmerse(0);
			}
			else {
				bannerControlVO.setIsTitleBarImmerse(Integer.parseInt(isTitleBarImmerse));
			}
			if (StringUtils.isBlank(isMyIconWhite)){
				bannerControlVO.setIsMyIconWhite(0);
			}
			else {
				bannerControlVO.setIsMyIconWhite(Integer.parseInt(isMyIconWhite));
			}
			if (getUploadTitleUrl() != null) {
				String dstPath = ServletActionContext.getServletContext().getRealPath(this.getSavePath());
				File out = new File(dstPath);
				if (!out.exists()) {
					out.mkdirs();
				}
				dstPath += File.separator + getUploadTitleUrlFileName();
				out = new File(dstPath);
				FileCopyUtils.copy(uploadTitleUrl, out);
				FileInputStream in = new FileInputStream(dstPath);
				// Zone为七牛机房所在地，根据源所在机房配置
				Configuration config = new Configuration(Zone.zone0());
				String imgUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
				in.close();
				bannerControlVO.setTitleUrl(imgUrl);
			}
			if (paramsMap.get("api") != null) {
				if(Integer.parseInt(paramsMap.get("displayWay").toString()) == 5 || Integer.parseInt(paramsMap.get("displayWay").toString()) == 6){
					String msg = "限制次数填写的必须是数字";
					if(Integer.parseInt(paramsMap.get("displayWay").toString()) == 6){
						 msg = "新用户指定间隔时间填写的必须是数字";
					}
					String limit = paramsMap.get("api").toString();
					if(!NumberUtil.isNumeric(limit)){
						paramsMap.put("status", -1);
						paramsMap.put("msg",msg);
						prepareBase();
						return Action.SUCCESS;
					}else if(Integer.parseInt(paramsMap.get("displayWay").toString()) == 6 &&  Integer.parseInt(limit) < 24){
						msg = "新用户指定间隔时间必须大于24";
						paramsMap.put("status", -1);
						paramsMap.put("msg",msg);
						prepareBase();
						return Action.SUCCESS;
					}
				}
				bannerControlVO.setApi(paramsMap.get("api").toString());
			}
			bannerControlVO.setStatus(1);
			bannerControlVO.setMustLogin(Integer.valueOf(mustLogin));
			if (StringUtils.isNotEmpty(badgestate)) {
				boolean isUpdate = true;
				BadgeInfo object = null;
				if (vo != null) {
					object = JSONUtils.fromJsonNew(vo.getBadge(), BadgeInfo.class);
					if (object != null && object.getState() != null && object.getState().intValue() == Integer.parseInt(badgestate) && object.getResident() != null
							&& object.getResident().intValue() == Integer.parseInt(badgeresident) && object.getText() != null && object.getText().equals(badgestext)) {
						isUpdate = false;
					}
				}
				if (isUpdate) {
					BadgeInfo info = new BadgeInfo();
					info.setState(Integer.parseInt(badgestate));
					if (info.getState().intValue() == IBadgeState.SHOW_TEXT || info.getState().intValue() == IBadgeState.SHOW_IMAGE) {
						info.setText(badgestext);
					}
					info.setResident(Integer.parseInt(badgeresident));
					info.setTimestamp(System.currentTimeMillis());
					bannerControlVO.setBadge(JSONUtils.toJson(info));
				} else {
					if (object != null) {
						bannerControlVO.setBadge(JSONUtils.toJson(object));
					}
				}
			}
			
			if (jsonArrayChannel != null) {
				bannerControlVO.setExcept_channel(jsonArrayChannel.toString());
			}
			
			String iconId = (String) paramsMap.get("iconId");
			String conditonType = (String) paramsMap.get("conditonType");
			String conditonValue = (String) paramsMap.get("conditonValue");
			if(StringUtils.isNotBlank(conditonType)) {   	//替换条件非空，用business_condition字段保存替补icon信息
				
				if(StringUtils.isBlank(iconId) || !NumberUtils.isNumber(iconId)) {
					throw new IllegalStateException("请输入正确的替补主键");
				}
				
				MainiconControlVO mainiconControlVO =  (MainiconControlVO) this.getService().findUniqueByHQL(" FROM MainiconControlVO vo where vo.id = ? AND vo.type = ?", NumberUtils.toLong(iconId), 7);
				if(Objects.isNull(mainiconControlVO)) {
					throw new IllegalStateException("请输入正确的替补主键");
				}
				
				if(NumberUtils.toInt(conditonType) == BannerIconCondition.CLICK_LOAN_ACTIVITY) {
					if(StringUtils.isBlank(conditonValue) || !NumberUtils.isNumber(conditonValue)) {
						throw new IllegalStateException("请输入贷款活动的替补值");
					}
				}
				
				BannerIconCondition bannerIconCondition = new BannerIconCondition();
				bannerIconCondition.bannerIconId = NumberUtils.toLong(iconId);
				bannerIconCondition.conditonType = NumberUtils.toInt(conditonType);
				bannerIconCondition.conditonValue = conditonValue;
				bannerControlVO.setBusiness_condition(new Gson().toJson(bannerIconCondition));
			}
			String title = null;
			
			bannerControlVO.setOperator(operator);
			if (StringUtils.isEmpty(id)) {
				this.getService().doCreate(MainiconControlVO.class, bannerControlVO);
				title = userVO.getUsername() + " 新增了 icon：" + bannerControlVO.getTitle();
			} else {
				bannerControlVO.setId(Long.valueOf(id));
				this.getService().doUpdate(MainiconControlVO.class, bannerControlVO);
				title = userVO.getUsername() + " 编辑了icon：" + bannerControlVO.getTitle() + ", id:" + bannerControlVO.getId();
			}
			
			List<String> emailAddredssList = new ArrayList<>();
			emailAddredssList.add("linhang@xmiles.cn");
			emailAddredssList.add("chenjiayu@xmiles.cn");
			
			String content = JSONUtils.toJsonString(bannerControlVO);
			
			if (TestMode.isTestMode()) {
				SendEmail.sendEmail(emailAddredssList, "测试环境：" + title, "修改后数据为：" + content);
			} else {
				SendEmail.sendEmail(emailAddredssList, title, "修改后数据为：" + content);
			}
			
//			String result = UpdateRedis.updateIcon(platform, Integer.valueOf(type));
//			if (JSONUtils.parseResult(result) != 1) {
//				JsonObject parser = (JsonObject) new JsonParser().parse(result);
//				throw new IllegalStateException(parser.getAsJsonPrimitive("msg").getAsString());
//			}
			
			updateIconCache(platform, Integer.valueOf(type));
			paramsMap.put("status", 1);
			prepareBase();

		} catch (Exception e) {
			e.printStackTrace();
			try {
				prepareBase();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			paramsMap.put("status", -1);
			paramsMap.put("msg", e.getMessage());
		}
		return Action.SUCCESS;
	}
	
	private void updateIconCache(String platform, Integer type) {
		String postUrl = Constant.COMMON_HOST + "/loan_service/common?funid=13&rd=" + System.currentTimeMillis();
		JsonObject requestjson = new JsonObject();
		requestjson.addProperty("platform", platform);
		requestjson.addProperty("type", type);

		// 请求数据
		FormData formdata = new FormData();
		formdata.addParam("handle", "0");
		formdata.addParam("data", requestjson.toString());
		formdata.addParam("shandle", "1");
		PostData postData = new PostData(formdata);

		try {
			// 请求数据
			HttpResult httpResult = HttpClientUtil.post(postUrl, postData);
			String response = ZipUtil.unCompressData(httpResult.getData());
			LogService.info("更新icon缓存：" + response);
		} catch (Exception e) {
			e.printStackTrace();
			LogService.error("更新icon缓存报错", e);
		}
	}

	public String list() {
		return super.list();
	}

	public void deleteBanner() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		if (StringUtils.isNotEmpty(id)) {
			MainiconControlVO vo = (MainiconControlVO) this.getService().findUniqueByHQL("From MainiconControlVO vo where vo.id = ?", Long.valueOf(id));
			// String key = "cmb:platform_" + vo.getPlatform() + "position_" +
			// vo.getPosition() + "type_" + vo.getType();
			// UpdateRedis.delKey(key);
			// key = "cmb:platform_" + vo.getPlatform() + "type_" +
			// vo.getType();
			// UpdateRedis.delKey(key);
//			this.getService().executeHQLUpdate("delete MainiconControlVO vo where vo.id = ?", Long.valueOf(id));
//			String result = UpdateRedis.updateIcon(vo.getPlatform(), vo.getType());
//			if (JSONUtils.parseResult(result) != 1) {
//				JsonObject parser = (JsonObject) new JsonParser().parse(result);
//				throw new IllegalStateException(parser.getAsJsonPrimitive("msg").getAsString());
//			}
			updateIconCache(vo.getPlatform(), vo.getType());
		}
		paramsMap.put("status", 1);
		JsonResult result = new JsonResult("1");
		try {
			sendJsonMessage(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void updateBanner() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String status = (String) paramsMap.get("status");
		if (StringUtils.isNotEmpty(id)) {
			this.getService().executeHQLUpdate("update MainiconControlVO vo set vo.status = ?, vo.operator = ? where vo.id = ?", Integer.valueOf(status), userVO.getUsername(), Long.valueOf(id));
			MainiconControlVO vo = (MainiconControlVO) this.getService().findUniqueByHQL("From MainiconControlVO vo where vo.id = ?", Long.valueOf(id));
			// String key = "cmb:platform_" + vo.getPlatform() + "position_" +
			// vo.getPosition() + "type_" + vo.getType();
			// UpdateRedis.delKey(key);
			// key = "cmb:platform_" + vo.getPlatform() + "type_" +
			// vo.getType();
			// UpdateRedis.delKey(key);

//			String result = UpdateRedis.updateIcon(vo.getPlatform(), vo.getType());
//			if (JSONUtils.parseResult(result) != 1) {
//				JsonObject parser = (JsonObject) new JsonParser().parse(result);
//				throw new IllegalStateException(parser.getAsJsonPrimitive("msg").getAsString());
//			}
			
			List<String> emailAddredssList = new ArrayList<>();
			emailAddredssList.add("dkzjdev@xmiles.cn");
			emailAddredssList.add("tzyy@xmiles.cn");	
			
			String title = null;
			// 上线了
			if ("1".equals(status)) {
				title = userVO.getUsername() + " 上线了 icon：" + vo.getTitle() + ", id:" + vo.getId();
			} else {
				title = userVO.getUsername() + " 下线了  icon：" + vo.getTitle() + ", id:" + vo.getId();
			}
			
			String content = JSONUtils.toJsonString(vo);
			
			if (TestMode.isTestMode()) {
				SendEmail.sendEmail("linhang@xmiles.cn", "chenjiayu@xmiles.cn", "测试环境：" + title, "修改后数据为：" + content);
			} else {
				SendEmail.sendEmail(emailAddredssList, title, "修改后数据为：" + content);
			}
			
			updateIconCache(vo.getPlatform(), vo.getType());
		}
		paramsMap.put("status", 1);
		JsonResult result = new JsonResult("1");
		try {
			sendJsonMessage(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}
	
	public File getUpload_click() {
		return upload_click;
	}

	public void setUpload_click(File upload_click) {
		this.upload_click = upload_click;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	
	public String getUpload_clickFileName() {
		return upload_clickFileName;
	}

	public void setUpload_clickFileName(String upload_clickFileName) {
		this.upload_clickFileName = upload_clickFileName;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	public static void main(String[] args) throws Exception {
		String json = "{ \"launch\": \"launch_main_tab\", \"launchParams\": { \"tab\": \"my\", \"title\": \"我的\", \"htmlUrl\": “2”} }";
		JSON.parse(json);
		JSONUtils.fromJsonNew(json, JsonObject.class);
		JsonParser jsonParser = new JsonParser();
		boolean flag = jsonParser.parse(json).isJsonObject();
		System.out.println(flag);
	}

	public File getUploadTitleUrl() {
		return uploadTitleUrl;
	}

	public void setUploadTitleUrl(File uploadTitleUrl) {
		this.uploadTitleUrl = uploadTitleUrl;
	}

	public String getUploadTitleUrlFileName() {
		return uploadTitleUrlFileName;
	}

	public void setUploadTitleUrlFileName(String uploadTitleUrlFileName) {
		this.uploadTitleUrlFileName = uploadTitleUrlFileName;
	}

	public String getUploadTitleUrlContentType() {
		return uploadTitleUrlContentType;
	}

	public void setUploadTitleUrlContentType(String uploadTitleUrlContentType) {
		this.uploadTitleUrlContentType = uploadTitleUrlContentType;
	}
}
